package com.anji.plus.modules.dict.service.impl;

import com.anji.plus.gaea.bean.KeyValue;
import com.anji.plus.gaea.cache.CacheHelper;
import com.anji.plus.gaea.constant.BaseOperationEnum;
import com.anji.plus.gaea.constant.Enabled;
import com.anji.plus.gaea.constant.GaeaConstant;
import com.anji.plus.gaea.constant.GaeaKeyConstant;
import com.anji.plus.gaea.curd.mapper.GaeaBaseMapper;
import com.anji.plus.gaea.exception.BusinessException;
import com.anji.plus.gaea.utils.GaeaUtils;
import com.anji.plus.modules.dict.dao.GaeaDictItemMapper;
import com.anji.plus.modules.dict.dao.GaeaDictMapper;
import com.anji.plus.modules.dict.dao.entity.GaeaDict;
import com.anji.plus.modules.dict.dao.entity.GaeaDictItem;
import com.anji.plus.modules.dict.service.GaeaDictService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (GaeaDict)ServiceImpl
 *
 * @author lr
 * @since 2021-02-23 10:01:02
 */
@Service
public class GaeaDictServiceImpl implements GaeaDictService {

    @Autowired
    private GaeaDictMapper  gaeaDictMapper;

    @Autowired
    private GaeaDictItemMapper gaeaDictItemMapper;

    @Autowired
    private CacheHelper cacheHelper;

    @Override
    public GaeaBaseMapper<GaeaDict> getMapper() {
        return  gaeaDictMapper;
    }

    /**
     * 处理字典分页，添加字典项
     * @param iPage
     * @return
     */
//    @Override
//    public IPage<GaeaDict> resultHandler(IPage<GaeaDict> iPage) {
//
//        List<GaeaDict> records = iPage.getRecords();
//
//        List<String> dictCodes = records.stream().map(GaeaDict::getDictCode).collect(Collectors.toList());
//
//        LambdaQueryWrapper<GaeaDictItem> wrapper = Wrappers.lambdaQuery();
//        wrapper.eq(GaeaDictItem::getEnabled, Enabled.YES.getValue()).in(GaeaDictItem::getDictCode, dictCodes);
//        List<GaeaDictItem> gaeaDictItems = gaeaDictItemMapper.selectList(wrapper);
//
//        Map<String, List<GaeaDictItem>> dictCodeItemMap = gaeaDictItems.stream().collect(Collectors.groupingBy(GaeaDictItem::getDictCode));
//
//        records.stream().forEach(gaeaDict -> gaeaDict.setChildren(dictCodeItemMap.get(gaeaDict.getDictCode())));
//
//        return iPage;
//    }

    @Override
    public void processAfterOperation(GaeaDict entity, BaseOperationEnum operationEnum) throws BusinessException {
        switch (operationEnum) {
            case INSERT:
            case UPDATE:
                refresh(entity.getDictCode());
                break;
            default:
        }
    }

    /**
     * 刷新缓存
     * @param dictCode
     */
    @Override
    public void refresh(String dictCode) {
        LambdaQueryWrapper<GaeaDictItem> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(GaeaDictItem::getDictCode, dictCode);
        //查询所有字典项
        List<GaeaDictItem> gaeaDictItems = gaeaDictItemMapper.selectList(wrapper);
        refreshCache(gaeaDictItems);

    }

    /**
     * 刷新全部缓存
     * @param gaeaDictItems
     */
    @Override
    public void refreshCache(List<GaeaDictItem> gaeaDictItems) {
        //对数据字典项进行分组，分组key=语言标识:字典编码
        Map<String, Map<String, String>> dictItemMap = gaeaDictItems.stream()
                .collect(Collectors
                        .groupingBy(item -> item.getDictCode() + GaeaConstant.REDIS_SPLIT +item.getLocale(),
                                Collectors.toMap(GaeaDictItem::getItemValue, GaeaDictItem::getItemName,(v1,v2)-> v2)));

        //遍历并保持到Redis中
        dictItemMap.entrySet().stream().forEach(entry -> {
            String key = GaeaKeyConstant.DICT_PREFIX  + entry.getKey();
            cacheHelper.delete(key);
            cacheHelper.hashSet(key, entry.getValue());
        });
    }

    /**
     * 根据国际化语言查询指定字典编码下拉列表
     * 先从Redis中获取
     * @param dictCode 字典名称
     * @param language 语言
     * @return
     */
    @Override
    public List<KeyValue> select(String dictCode, String language) {

        //缓存字典Key
        String dictKey = GaeaKeyConstant.DICT_PREFIX + dictCode + GaeaConstant.REDIS_SPLIT + language;

        Map<String, String> dictMap = cacheHelper.hashGet(dictKey);

        //当查询的字典为空时
        if (CollectionUtils.isEmpty(dictMap)) {
            LambdaQueryWrapper<GaeaDictItem> wrapper = Wrappers.lambdaQuery();
            wrapper.eq(GaeaDictItem::getDictCode, dictCode)
                    .eq(GaeaDictItem::getEnabled, Enabled.YES.getValue())
                    .eq(GaeaDictItem::getLocale, language)
                    .orderByAsc(GaeaDictItem::getSort);

            List<GaeaDictItem> list = gaeaDictItemMapper.selectList(wrapper);

            List<KeyValue> keyValues = list.stream()
                    .map(dictItemEntity -> new KeyValue(dictItemEntity.getItemValue(),dictItemEntity.getItemName()))
                    .collect(Collectors.toList());
            //当缓存不存在时，刷新缓存
            refreshCache(list);
            return keyValues;
        }

        return GaeaUtils.formatKeyValue(dictMap);
    }

    @Override
    public List<GaeaDictItem> findAllItem() {
        return gaeaDictItemMapper.selectList(Wrappers.emptyWrapper());
    }
}
